package cn.edu.zut.hkxy.controller;

import cn.edu.zut.hkxy.util.FileUploadUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@Controller
@RequestMapping(value = "/upload")
public class FileUploadController {

    @RequestMapping(value = "/image")
    public void uploadImg(@RequestParam(value = "upload") MultipartFile img,
                          HttpServletResponse response,
                          HttpServletRequest request) throws IOException{
        String imgsSuff=".png .jpg .jpeg .gif .bmp";
        String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
        PrintWriter out=response.getWriter();
        String originalName=img.getOriginalFilename();
        String suffix=originalName.substring(originalName.lastIndexOf("."));
        if(!imgsSuff.contains(suffix.toLowerCase())){
            //文件格式不符合，返回错误信息
            out.println("<script type=\"text/javascript\">");
            out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
                    + ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");
            out.println("</script>");
        }else {
            //图片保存到服务器
        //    String path = "F:/Tomcat8/hkxyFilesServer/images/";
            String path=FileUploadUtils.getPathOrUrl(FileUploadUtils.imgPath);
            String name= UUID.randomUUID().toString()+originalName.substring(originalName.lastIndexOf("."));
            File file=new File(path,name);
            System.out.println(file.getPath());
            img.transferTo(file);

         //   String fileURL="http://localhost/file/images/"+name;
            String fileURL=FileUploadUtils.getPathOrUrl(FileUploadUtils.imgUrlPrefix)+name;
            //String fileURL=request.getContextPath()+"/upluad/images/"+name;
            // 返回"图像"选项卡和图像在服务器的地址并显示图片
            out.println("<script type=\"text/javascript\">");
            out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" +fileURL+"','')");
            out.println("</script>");
            out.close();
        }
    }
}
